<script setup>
import { ref, watch, computed, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const props = defineProps({
  folder: String,
  selectedPath: String
})

const emit = defineEmits(['select', 'path-select'])

// 状态管理
const state = reactive({
  subFolders: [],
  loading: false,
  searchQuery: '',
  editingFolder: null
})

// 搜索结果
const filteredFolders = computed(() => {
  if (!state.searchQuery) return state.subFolders
  
  const query = state.searchQuery.toLowerCase()
  return state.subFolders.filter(folder => 
    folder.name.toLowerCase().includes(query)
  )
})

// 加载子文件夹
const loadSubFolders = async (folderPath) => {
  if (!folderPath) {
    state.subFolders = []
    return
  }

  state.loading = true
  try {
    const folders = await window.mediaManager.getSubFolders(folderPath)
    state.subFolders = folders.map(folder => ({
      path: folder.path,
      name: folder.name,
      isSelected: folder.path === props.selectedPath
    }))
  } catch (error) {
    console.error('Load subfolders failed:', error)
    ElMessage.error('加载子文件夹失败')
  } finally {
    state.loading = false
  }
}

// 选择主文件夹
const handleSelect = () => {
  emit('select')
}

// 选择子文件夹
const selectSubFolder = (folder) => {
  state.subFolders.forEach(f => f.isSelected = f.path === folder.path)
  emit('path-select', folder.path)
}

// 创建新文件夹
const createFolder = async () => {
  if (!props.folder) return
  
  try {
    const folderName = state.searchQuery.trim()
    if (!folderName) return
    
    const newPath = await window.mediaManager.createFolder(props.folder, folderName)
    if (newPath) {
      state.searchQuery = ''
      loadSubFolders(props.folder)
      ElMessage.success('文件夹创建成功')
    }
  } catch (error) {
    console.error('Create folder failed:', error)
    ElMessage.error('创建文件夹失败')
  }
}

// 重命名文件夹
const renameFolder = async (folder) => {
  try {
    const { value: newName } = await ElMessageBox.prompt('请输入新的文件夹名称', '重命名文件夹', {
      inputValue: folder.name,
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })
    
    if (newName && newName !== folder.name) {
      await window.mediaManager.renameFolder(folder.path, newName)
      loadSubFolders(props.folder)
      ElMessage.success('重命名成功')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Rename folder failed:', error)
      ElMessage.error('重命名失败')
    }
  }
}

// 删除文件夹
const deleteFolder = async (folder) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除此文件夹吗？此操作不可恢复。',
      '删除文件夹',
      {
        type: 'warning',
        confirmButtonText: '删除',
        cancelButtonText: '取消'
      }
    )
    
    await window.mediaManager.deleteFolder(folder.path)
    loadSubFolders(props.folder)
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Delete folder failed:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 监听主文件夹变化时重新加载子文件夹
watch(() => props.folder, (newFolder) => {
  if (newFolder) {
    loadSubFolders(newFolder)
  }
}, { immediate: true })

// 监听选中路径变化时更新选中状态
watch(() => props.selectedPath, (newPath) => {
  if (state.subFolders.length > 0) {
    state.subFolders.forEach(f => f.isSelected = f.path === newPath)
  }
}, { immediate: true })
</script>

<template>
  <div class="folder-panel">
    <div class="panel-header">
      <h2>目标文件夹</h2>
      <el-button @click="handleSelect">选择文件夹</el-button>
    </div>
    
    <div v-if="folder" class="folder-path">
      {{ folder }}
    </div>
    
    <!-- 搜索框 -->
    <div class="search-box" v-if="folder">
      <el-input
        v-model="state.searchQuery"
        placeholder="搜索或输入新文件夹名称"
        clearable
      >
        <template #append>
          <el-button @click="createFolder">
            <el-icon><Plus /></el-icon>
            创建
          </el-button>
        </template>
      </el-input>
    </div>
    
    <!-- 子文件夹列表 -->
    <div class="subfolder-list" v-if="filteredFolders.length > 0">
      <div
        v-for="folder in filteredFolders"
        :key="folder.path"
        class="subfolder-item"
        :class="{ selected: folder.isSelected }"
      >
        <div class="folder-info" @click="selectSubFolder(folder)">
          <el-icon><Folder /></el-icon>
          <span class="folder-name">{{ folder.name }}</span>
        </div>
        <div class="folder-actions">
          <el-button 
            text 
            type="primary" 
            @click="renameFolder(folder)"
          >
            <el-icon><Edit /></el-icon>
          </el-button>
          <el-button 
            text 
            type="danger" 
            @click="deleteFolder(folder)"
          >
            <el-icon><Delete /></el-icon>
          </el-button>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-else-if="state.loading" class="loading-state">
      <el-icon class="loading"><Loading /></el-icon>
      加载中...
    </div>

    <!-- 空状态 -->
    <div v-else class="empty-state">
      <el-empty 
        :description="
          folder 
            ? state.searchQuery 
              ? '没有找到相关文件夹，按回车创建新文件夹'
              : '没有子文件夹' 
            : '请选择目标文件夹'
        " 
      />
    </div>
  </div>
</template>

<style scoped>
.folder-panel {
  flex: 2; /* 增加宽度占比 */
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.search-box {
  padding: 12px;
  border-bottom: 1px solid #eee;
}

.subfolder-list {
  flex: 1;
  overflow-y: auto;
  padding: 12px;
}

.subfolder-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  border-radius: 6px;
  transition: all 0.3s;
}

.subfolder-item:hover {
  background: #f5f7fa;
}

.subfolder-item.selected {
  background: var(--el-color-primary-light-9);
}

.folder-info {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
  min-width: 0;
  cursor: pointer;
}

.folder-name {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.folder-actions {
  display: flex;
  gap: 4px;
  opacity: 0;
  transition: opacity 0.3s;
}

.subfolder-item:hover .folder-actions {
  opacity: 1;
}

.panel-header {
  padding: 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.panel-header h2 {
  margin: 0;
  color: #303133;
}

.folder-path {
  padding: 10px 20px;
  background: #f5f7fa;
  color: #606266;
  font-size: 14px;
  border-bottom: 1px solid #eee;
}

.loading-state {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 20px;
  color: #909399;
}

.empty-state {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.loading {
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
</style> 